package cn.wgd.zmx.service;

import cn.wgd.zmx.common.exception.EmException;
import cn.wgd.zmx.common.result.Response;
import cn.wgd.zmx.controller.c_model.UserModel;
import cn.wgd.zmx.domain.User;
import cn.wgd.zmx.mapper.UserMapper;
import cn.wgd.zmx.utils.MD5Utils;
import cn.wgd.zmx.utils.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public Response list() {
        return new Response(0, "执行成功！", 1, userMapper.selectAll());
    }

    public Response del(Integer id) {
        userMapper.deleteByPrimaryKey(id);
        return new Response(0, "删除成功！");
    }

    public Response add(UserModel user) {
        User u = new User();
        BeanUtils.copyProperties(user, u);
        u.setUpdateTime(new Date());
        u.setPassword(MD5Utils.encode(u.getPassword()));
        if (isNameLive(user.getName())) {
            return new Response(EmException.USER_ISLIVE);
        }
        userMapper.insert(u);
        return new Response(0, "增加成功！");
    }

    public Response updateUser(UserModel user) {
        User u = new User();
        BeanUtils.copyProperties(user, u);
        u.setUpdateTime(new Date());
        /**
         * 防止前面没有输入更新人，这里读取当前用户，待做
         */
        if (isNameLive(user.getName())) {
            return new Response(EmException.USER_ISLIVE);
        }
        userMapper.updateByPrimaryKey(u);
        return new Response(0, "更新成功！");
    }

    /**
     * 用户名不能重复,数据库已添加唯一索引
     */
    private boolean isNameLive(String name) {
        User user = userMapper.selectByName(name);
        if (user == null) {
            return false;
        } else {
            return true;
        }
    }

    public Response searchByName(String name) {
        name = "%" + name + "%";
        return new Response(0, "搜索成功！", 1, userMapper.selectByNameLike(name));
    }
}
